import json
from idlelib import debugger
from backend.models import BackendUser

from django.contrib.auth import authenticate
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt



# 登录视图
# @csrf_exempt  # 禁用 CSRF 校验
def login(request):
    if request.method == 'POST':
        print('xxx')
        try:
            # 获取请求中的用户名和密码
            data = json.loads(request.body)
            username = data.get('username')
            password = data.get('password')

            # 验证用户名和密码
            user = checkUser(username=username, password=password)
            if user is not None:
                # 认证成功，生成 token (可以用 JWT 或其他方式生成)
                token = "your_generated_token"  # 假设这是生成的 token
                user_info = {
                    "username": user.username,
                    # "email": user.email,
                    # 其他用户信息
                }
                return JsonResponse({
                    "token": token,
                    "userInfo": user_info
                })
            else:
                return JsonResponse({"error": "Invalid credentials"}, status=400)
        except json.JSONDecodeError as e:
            print(e)
            return JsonResponse({"error": "Invalid JSON"}, status=400)
    else:
        return JsonResponse({"error": "Only POST method is allowed"}, status=405)

def checkUser(username, password):
    user = BackendUser.objects.filter(username=username).first()
    if user:
        if user.password == password:
            return user
    else:
        None